//
//  MembersViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-10-21.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "MembersViewController.h"
#import "ASImageView.h"
#import "JSONRequest.h"
#import "JMFBase.h"
#import "PersonalViewController.h"
#import <MessageUI/MessageUI.h>
#import "InvitationOptionsViewController.h"
#import "MJRefresh.h"

@interface MembersViewController ()<MJRefreshBaseViewDelegate, JSONRequestDelegate, UIActionSheetDelegate, UIAlertViewDelegate>

@end

@implementation MembersViewController
{
    NSMutableArray *_membersArray;
    
    NSDictionary *_currentInvited;               //邀请中的好友中被选中的好友信息对象
    
    NSIndexPath *_currentRelieves;               //当前要取消屏蔽的用户所在数据源的位置
    
    NSIndexPath *_currentReinvite;               //当前要重新发送邀请的已注册用户的索引
    
    MJRefreshFooterView *_footer;
    MJRefreshHeaderView *_header;
}

@synthesize circle = _circle;
@synthesize membersType = _membersType;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        _membersType = MembersNormalType;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //左侧按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    backButton.tag = 100;
    [backButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    if (_membersType == MembersNormalType) {
        
        self.title = [_circle valueForKey:@"name"];
        
        //右侧按钮：添加
        UIButton* addButton = [Helper buttonWithStyle:ButtonStyleNavigationAdd];
        addButton.tag = 101;
        [addButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    }
    else if (_membersType == MembersInvitingType) {
        self.title = _L(@"title_92");
        
        //右侧按钮：添加
        UIButton* clearButton = [Helper buttonWithStyle:ButtonStyleNavigationClear];
        clearButton.tag = 102;
        [clearButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:clearButton];
    }
    else if (_membersType == MembersBanType) {
        self.title = _L(@"title_93");
    }
    
    // 3.3行集成下拉刷新控件
    _header = [MJRefreshHeaderView header];
    _header.scrollView = self.tableView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.delegate = self;
    
    _membersArray = [NSMutableArray new];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [_header beginRefreshing];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 事件

- (void)buttonEvent:(id)sender
{
    UIButton *clickedButton = (UIButton *)sender;
    
    //返回
    if (clickedButton.tag == 100) {
        [self.navigationController popViewControllerAnimated:YES];
    }

    //添加
    else if (clickedButton.tag == 101) {
        
        if (_circle == nil) {
            return;
        }
        
        NSMutableArray* names = [[NSMutableArray alloc] init];
        NSMutableArray* ids = [[NSMutableArray alloc] init];

        [names addObject:[_circle objectForKey:@"name"]];
        [ids addObject:[NSNumber numberWithInteger:[[_circle objectForKey:@"id"] integerValue]]];
        
        [Helper cacheCircleWithIds:ids andNames:names];
        
        
        InvitationOptionsViewController *invitationOptionsVC = [[InvitationOptionsViewController alloc] init];
        invitationOptionsVC.navigationItem.title = [_circle objectForKey:@"name"];
        invitationOptionsVC.backMode = YES;
        UINavigationController *invitationOptionsNC = [[UINavigationController alloc] initWithRootViewController:invitationOptionsVC];
        [Helper navigationControllerCommonStyle:invitationOptionsNC];
        
        [self.navigationController presentModalViewController:invitationOptionsNC animated:YES];
    }
    //清空
    else if (clickedButton.tag == 102) {
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:_L(@"alert_129")] delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        
        [alertView show];
    }
    else {
        
    }
}


//点击自定义的accessoryButton时，让tableview相应accessoryButton的代理方法
- (void)cancelBtnClicked:(id)sender event:(id)event
{
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath= [self.tableView indexPathForRowAtPoint:currentTouchPosition];
    if (indexPath!= nil)
    {
        [self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
    }
}

////头像被点击所触发的按钮，此方法用于响应头像被点击的事件
////点击通过手势来实现，通过获取点击的坐标来对应到tableview的cell，以此来获取被点击的indexpath，从而从数据源中获取数据
//- (void)avatarTapped:(id)sender
//{
//    UITapGestureRecognizer *tapGestureRecognizer = (UITapGestureRecognizer *)sender;
//
//    CGPoint currentTouchPosition = [tapGestureRecognizer locationInView:self.tableView];
//    
//    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
//    
//    NSDictionary *friend = [_membersArray objectAtIndex:indexPath.row];
//    
//    if (indexPath != nil) {
//        
//        PersonalInfoViewController *personalInfoVC = [[PersonalInfoViewController alloc] initWithPersonId:[friend[@"userId"] integerValue]];
//        [self.navigationController pushViewController:personalInfoVC animated:YES];
//    }
//}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return _membersArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        ASImageView* imageView = [[ASImageView alloc] initWithFrame:CGRectMake(8, 5, 30, 30)];
        imageView.image = [UIImage imageNamed:@"dynamic_btn_001"];
        
        [cell.contentView addSubview:imageView];
    
        UILabel* contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 5, 200, 35)];
        contentLabel.font = _SYS_FONT_003;
        contentLabel.textColor = _SYS_COLOR_002;
        contentLabel.lineBreakMode = UILineBreakModeWordWrap;
        contentLabel.numberOfLines = 0;
        contentLabel.textColor = [UIColor blackColor];
        contentLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:contentLabel];
        
        if (_membersType == MembersNormalType) {
            
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
        }
        else if (_membersType == MembersInvitingType) {
            
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        
        else if (_membersType == MembersBanType) {
            
            //取消屏蔽
            UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 45.0f, 23.7f)];
            [cancelButton setBackgroundImage:[UIImage imageNamed:@"transaction_btn_002_n"] forState:UIControlStateNormal];
            [cancelButton setTitle:_L(@"btn_title_05") forState:UIControlStateNormal];
            cancelButton.titleLabel.font = _SYS_FONT_001;
            [cancelButton addTarget:self action:@selector(cancelBtnClicked:event:) forControlEvents:UIControlEventTouchUpInside];
            cell.accessoryView = cancelButton;
        }
        else{
            
        }
    }
    
    NSDictionary* member = [_membersArray objectAtIndex:indexPath.row];
    
    //设置本行的row值给图片，图片点击的时候就可以通过_dataSource的row行获取到Circle对象
    [[cell.contentView.subviews objectAtIndex:0] setTag:indexPath.row];
    
    ASImageView *imageView = (ASImageView *)[cell.contentView.subviews objectAtIndex:0];
    if ([[member objectForKey:@"previewAvatar"] length] > 0) {
        [imageView setImageURL:[NSURL URLWithString:[member objectForKey:@"previewAvatar"]] andSourceImageURL:nil forStyle:PictureStyleAvartPreview];
    }
    
    if (_membersType == MembersNormalType) {
        
        [((UILabel *)[cell.contentView.subviews objectAtIndex:1]) setText:[member objectForKey:@"name"]];
    }
    else if (_membersType == MembersInvitingType) {
        
        //如果用户未注册，就显示remarkname
        //如果用户注册，就显示realname（remarkname ），没有realname 就只显示remarkname
        //type  0:未注册用户，1：注册用户
        
        if ([[member objectForKey:@"type"] integerValue] == 1 &&
            [[member objectForKey:@"realName"] length] != 0 &&
            !([[member objectForKey:@"realName"] isEqualToString:[member objectForKey:@"remarkName"]]))
        {
            [((UILabel *)[cell.contentView.subviews objectAtIndex:1]) setText:[NSString stringWithFormat:@"%@（%@）",[member objectForKey:@"realName"],[member objectForKey:@"remarkName"]]];
        }
        else
        {
            [((UILabel *)[cell.contentView.subviews objectAtIndex:1]) setText:[member objectForKey:@"remarkName"]];
        }
    }
    
    else if (_membersType == MembersBanType) {
        [((UILabel *)[cell.contentView.subviews objectAtIndex:1]) setText:[member objectForKey:@"realName"]];
    }
    else{
        
    }
    

    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:true];

    //普通列表下，被点击应该去个人详情页
    //邀请中的列表下，被点击应该弹出actionsheet
    //屏蔽中的列表下，不支持被点击
    if (_membersType == MembersNormalType) {
        
        NSInteger personalID = [[[_membersArray objectAtIndex:indexPath.row] valueForKey:@"memberId"] integerValue];
        PersonalInfoViewController* personalInfoVC = [[PersonalInfoViewController alloc] initWithPersonId:personalID];
        [self.navigationController pushViewController:personalInfoVC animated:true];
    }
    else if (_membersType == MembersInvitingType) {
        
        _currentInvited = [_membersArray objectAtIndex:indexPath.row];
        
        //发送邀请 判断注册或未注册
        if ([_currentInvited[@"type"] integerValue]) {
            UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:nil destructiveButtonTitle:_L(@"title_invite_07") otherButtonTitles: _L(@"btn_no_01"), nil];
            actionSheet.tag = 200;
            [actionSheet showInView:self.view];
            
            _currentReinvite = indexPath;
        }
        else {
            UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:nil destructiveButtonTitle:_L(@"title_invite_01") otherButtonTitles:_L(@"title_invite_02"), _L(@"btn_no_01"), nil];
            actionSheet.tag = 201;
            [actionSheet showInView:self.view];
        }
        
        
    }
    else if (_membersType == MembersBanType) {
        
        NSDictionary *friend = [_membersArray objectAtIndex:indexPath.row];
        PersonalInfoViewController *personalInfoVC = [[PersonalInfoViewController alloc] initWithPersonId:[friend[@"userId"] integerValue]];
        [self.navigationController pushViewController:personalInfoVC animated:YES];
    }
    else{
        
    }

}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    _currentRelieves = indexPath;
    
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_BAN_LIST_RECOVER];
    request.hudOn = true;
    request.hudTitle = _L(@"title_loading_01");
    request.delegate = self;
    [request setSuccessSelector:@selector(userDidRelieved:)];
    [request setValue:_membersArray[indexPath.row][@"userId"] forParameter:@"blacklistUserId"];
    [request asynchronous];
}

#pragma mark - 私有方法

- (void)obtainMembersWithCheckId:(NSInteger)checkId
{
    
    NSString *url = nil;
    
    if (_membersType == MembersNormalType) {
        
        url = _JSON_URL_CIRCLE_MEMBER_LIST;
    }
    else if (_membersType == MembersInvitingType) {
        
        url = _JSON_URL_CIRCLE_MEMBER_INVITE_LIST;
    }
    else if (_membersType == MembersBanType) {
        url = _JSON_URL_BAN_LIST;
    }
    else{
        url = _JSON_URL_CIRCLE_MEMBER_LIST;
    }
    
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:url];
    request.delegate = self;
    
    if (_membersType == MembersNormalType) {
        [request setValue:[_circle objectForKey:@"id"]  forParameter:@"circleId"];
        
    }
    if (checkId != 0) {
        [request setValue:[NSNumber numberWithInteger:checkId] forParameter:@"checkId"];
        
        [request setSuccessSelector:@selector(moreMembersDidReceived:)];
    }
    
    [request asynchronous];
}

/*!
 @abstract 获取数据源最后一条数据的id
 @discussion 用于分页功能
 @result 数据源最后一条数据的id
 */
- (NSInteger)catchTheLastDataSourceId
{
    NSInteger lastID = 0;
    if (_membersArray.count > 0) {
        
        lastID = [[_membersArray lastObject][@"id"] integerValue];
    }
    return lastID;
}

//刷新tableview
- (void)reloadTableView
{
    [self.tableView reloadData];
    // 结束刷新状态
    [_header endRefreshing];
    [_footer endRefreshing];
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
    
        if (_membersArray.count != 0) {
            [_membersArray removeAllObjects];
        }
        
        //将每次下拉刷新出的新数据都加入到数据源的最前面
        if ([(NSArray *)jmf.data count] != 0) {
            
            [_membersArray addObjectsFromArray:(NSArray *)jmf.data];
            
            _footer.scrollView = self.tableView;
        }
        
        if (_membersArray.count != 0) {
            self.tableView.tableFooterView.hidden = NO;
            self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        }
        else {
            self.tableView.tableFooterView.hidden = YES;
            self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        }
        
        [self reloadTableView];
        
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)moreMembersDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if ([(NSArray *)jmf.data count] != 0) {
            self.tableView.tableFooterView.hidden = NO;
            [_membersArray addObjectsFromArray:(NSArray *)jmf.data];
            
        }
        else{
            self.tableView.tableFooterView.hidden = YES;
        }
        [self reloadTableView];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

//好友被重新邀请请求成功
- (void)userDidReinvited:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        [Helper showAllTextDialog:jmf.message inSeconds:1.5f];
        
    }
}

//好友被被解除屏蔽请求成功
- (void)userDidRelieved:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        [Helper showAllTextDialog:jmf.message inSeconds:1.5f];
        
        if (_currentRelieves != nil) {
            
            [_membersArray removeObjectAtIndex:_currentRelieves.row];
            
            [self.tableView reloadData];
            
            _currentRelieves = nil;
        }
    }
}

//成员被清除请求成功
- (void)memberDidCleared:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        [Helper showAllTextDialog:jmf.message inSeconds:1.5f];
        [_membersArray removeAllObjects];
        
        [self.tableView reloadData];
        
    }
}


//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

#pragma mark - UIActionSheet Delegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //注册用户,重新发送邀请
    if (actionSheet.tag == 200) {
        
        if (buttonIndex == 0) {
            JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_FRIEND_INVITE_REPEAT];
            request.hudOn = true;
            request.hudTitle = _L(@"title_loading_01");
            request.delegate = self;
            [request setSuccessSelector:@selector(userDidReinvited:)];
            [request setValue:_membersArray[_currentReinvite.row][@"id"] forParameter:@"inviteId"];
            [request asynchronous];
        }
        
    }
    
    //非注册用户
    else if (actionSheet.tag == 201) {
        
        if (_currentInvited == nil) {
            [Helper showAlertWithTitle:@"" andMessage:_L(@"alert_54")];
            return;
        }
        
        //重新发送短信
        if (buttonIndex == 0) {
            
            NSMutableArray *mobileArray = [[NSMutableArray alloc] initWithObjects:[_currentInvited objectForKey:@"invitePhone"], nil];
            
            MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
            picker.messageComposeDelegate = (id)self;
            
            picker.body = _L(@"tpl_00");
            picker.recipients = mobileArray;
            
            [self presentModalViewController:picker animated:YES];
            
        }
        //重新打电话
        else if (buttonIndex == 1) {
            
            NSString *number = [NSString stringWithFormat:@"telprompt://%@", [_currentInvited objectForKey:@"invitePhone"]];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:number]];
            
        }
    }
    
    else {
        
        
    }
}

#pragma mark - UIAlertView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_MEMBER_INVITE_CLEAR];
        request.hudOn = true;
        request.hudTitle = _L(@"title_loading_01");
        request.delegate = self;
        
        [request setSuccessSelector:@selector(memberDidCleared:)];
        [request asynchronous];
        
    }
}

#pragma mark - SMS Delegate

// 短信发送状态通知协议方法
//
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    switch (result)
    {
        case MessageComposeResultCancelled:
            break;
        case MessageComposeResultSent:
            break;
        case MessageComposeResultFailed:
            break;
        default:
            break;
    }
    
    //必须放在这里，要让case 1内的语句先执行，才能使viewDidAppear获取到正确的值
    [controller dismissModalViewControllerAnimated:true];
}


#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //下拉刷新
    if (refreshView == _header) {
        
        //请求初始数据
        [self obtainMembersWithCheckId:0];
    }
    
    //上拉加载更多
    else {
        
        if ([self catchTheLastDataSourceId] != 0) {
            [self obtainMembersWithCheckId:[self catchTheLastDataSourceId]];
        }
    }

}

- (void)dealloc
{
    _membersArray = nil;
}

@end
